<template>
  <div class="app-container">
    <!-- 客户合同维护 -->

    <div class="search-bar" px-8>
      <!-- 搜索 -->
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <!-- <el-form-item label="合同编号" prop="companyCode">
          <el-select-v2
            v-model="queryParams.code"
            filterable
            clearable
            :options="allContractCode"
            value-key="value"
            placeholder="请输入合同编号"
            style="width: 240px"
            @change="handleQuery()"
          />
        </el-form-item> -->

        <el-form-item label="客户编号" prop="companyCode">
          <el-select-v2
            v-model="queryParams.companyCode"
            filterable
            clearable
            :options="allCompanyCode"
            value-key="value"
            placeholder="请输入客户编号"
            class="!w-[192px]"
            @change="handleQuery()"
          />
        </el-form-item>

        <el-form-item label="客户名称" prop="companyName">
          <el-input
            v-noSpace
            v-model="queryParams.companyName"
            placeholder="请输入客户名称"
            class="!w-[192px]"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="业务员" prop="salesMan">
          <!-- <el-select v-model="queryParams.salesMan" placeholder="请选择业务员" style="width: 250px" filterable clearable
            @change="handleQuery">
            <el-option v-for="item in salesPersonList" :key="item.value" :label="item.label" :value="item.value" /> -->
          <!-- </el-select> -->
          <el-select
            v-model="queryParams.salesMan"
            filterable
            clearable
            placeholder="请输入业务员"
            class="!w-[192px]"
            @change="handleQuery()"
          >
            <el-option
              v-for="item in salesPersonList"
              :key="item.value"
              :label="item.label"
              :value="item.value.toString()"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            class="!w-[192px]"
            clearable
            filterable
            @change="handleQuery()"
          >
            <el-option value="0" label="待审核" />
            <el-option value="1" label="正常履行" />
            <el-option value="2" label="审核拒绝" />
            <el-option value="3" label="异常终止" />
            <el-option value="4" label="正常到期" />
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期" prop="signDate">
          <el-date-picker
            v-model="queryParams.signDate"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery()"
            clearable
          />
        </el-form-item>

        <el-form-item label="失效日期" prop="expireDate">
          <el-date-picker
            v-model="queryParams.expireDate"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
          <el-button
            type="warning"
            icon="menu"
            @click="handleOpenDialog()"
            v-hasPerm="'sys:conManagement:edit'"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 合同列表 -->
    <el-card shadow="never">
      <el-table v-loading="loading" :data="pageData" show-overflow-tooltip>
        <el-table-column prop="code" label="合同编号" align="center" />
        <el-table-column prop="companyCode" label="客户编号" align="center" min-width="120" />
        <el-table-column prop="companyName" label="客户名称" align="center" />

        <el-table-column prop="salesMan" label="业务员" align="center">
          <template #default="scope">
            {{
              salesPersonList.filter((item) => item.value.toString() == scope.row.salesMan)[0]
                ?.label
            }}
          </template>
        </el-table-column>
        <el-table-column prop="discountRate" label="折扣率" align="center">
          <template #default="scope">{{ scope.row.discountRate }}%</template>
        </el-table-column>
        <el-table-column prop="signDate" label="签订时间" align="center" />
        <el-table-column prop="expireDate" label="到期时间" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status == 1" type="success">正常履行</el-tag>
            <el-tag v-if="scope.row.status == 2" type="warning">审核拒绝</el-tag>
            <el-tag v-if="scope.row.status == 3" type="danger">异常终止</el-tag>
            <el-tag v-if="scope.row.status == 4" type="warning">到期终止</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核意见" prop="auditOpinion" align="center" />
        <el-table-column label="备注" prop="remark" align="center" />

        <el-table-column label="操作" width="200px" fixed="right" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.status == 0 || scope.row.status == 2"
              type="primary"
              link
              size="small"
              @click="handleOpenApplyDialog(scope.row)"
              v-hasPerm="'sys:conManagement:app'"
            >
              审核
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'look')"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleOpenDialog(scope.row, 'update')"
              v-hasPerm="'sys:conManagement:edit'"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              v-hasPerm="'sys:conManagement:del'"
              link
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 查看，新增 -->
    <el-dialog
      v-model="contractDialog.visible"
      :title="contractDialog.title"
      width="1000px"
      @close="handleCloseDialog"
    >
      <!-- <el-scrollbar height="600px"> -->
      <div class="bg-gray-50 py-6">
        <div class="mx-auto max-w-7xl px-4">
          <el-form
            ref="contractFormRef"
            :model="contractFormData"
            :rules="contractRules"
            :disabled="contractDialog.type == 'look'"
            label-width="120px"
          >
            <!-- 合同信息 -->
            <div class="grid grid-cols-2 gap-2">
              <el-form-item label="客户编号：" prop="companyCode">
                <el-select-v2
                  v-model="contractFormData.companyCode"
                  filterable
                  clearable
                  :options="allCompanyCode"
                  value-key="companyName"
                  placeholder="请选择客户编号"
                  @change="getCusInfo(contractFormData.companyCode as string)"
                />
              </el-form-item>
              <el-form-item label="客户名称：" prop="companyName">
                <el-input
                  v-noSpace
                  v-model="contractFormData.companyName"
                  class="flex-1"
                  placeholder="请输入客户名称"
                  disabled
                />
              </el-form-item>
              <!-- <el-form-item label="合同状态：" prop="status" label-width="100px">
                  <el-select v-model="contractFormData.status">
                    <el-option value="0" label="待审核" />
                    <el-option value="1" label="正常履行" />
                    <el-option value="2" label="异常终止" />
                    <el-option value="3" label="正常到期" />
                  </el-select>
                </el-form-item> -->

              <el-form-item label="签订日期：" prop="signDate">
                <el-date-picker
                  v-model="contractFormData.signDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                  class="flex-1"
                  :disabled-date="disabledDate"
                />
              </el-form-item>

              <el-form-item label="到期日期：" prop="expireDate">
                <el-date-picker
                  v-model="contractFormData.expireDate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="flex-1"
                  :disabled-date="disabledDate"
                />
              </el-form-item>

              <el-form-item label="付款条款：" prop="paymentTerms">
                <el-select
                  v-model="contractFormData.paymentTerms"
                  class="flex-1"
                  multiple
                  clearable
                >
                  <el-option
                    v-for="item in paymentTermsList"
                    :key="item.codeValue"
                    :label="item.codeName"
                    :value="item.codeValue"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="交易条款：" prop="transactionTerms">
                <el-select
                  v-model="contractFormData.transactionTerms"
                  multiple
                  clearable
                  class="flex-1"
                >
                  <el-option
                    v-for="item in contractList"
                    :key="item.codeValue"
                    :label="item.codeName"
                    :value="item.codeValue"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="违约条款：" prop="breachType">
                <el-select v-model="contractFormData.breachType" class="flex-1" multiple clearable>
                  <el-option
                    v-for="item in breachList"
                    :key="item.codeValue"
                    :label="item.codeName"
                    :value="item.codeValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="折扣率：" prop="discountRate">
                <el-input-number
                  v-model="contractFormData.discountRate"
                  class="flex-1"
                  :min="0"
                  :max="100"
                >
                  <template #suffix>%</template>
                </el-input-number>
              </el-form-item>
              <el-form-item label="联系人：" prop="contactPerson">
                <el-select
                  v-model="contractFormData.contactPerson"
                  filterable
                  clearable
                  placeholder="请输入联系人"
                  @change="getContactInfo"
                >
                  <el-option
                    v-for="item in contactList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="联系电话：" prop="contactInfo">
                <el-input
                  v-noSpace
                  v-model="contractFormData.contactInfo"
                  placeholder=""
                  class="flex-1"
                  disabled
                />
              </el-form-item>

              <el-form-item label="业务员：" prop="salesMan">
                <el-select
                  v-model="contractFormData.salesMan"
                  filterable
                  clearable
                  placeholder="请输入业务员："
                  class="flex-1"
                >
                  <el-option
                    v-for="item in salesPersonList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value.toString()"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 备注信息 -->

            <el-form-item label="备注：" prop="remark">
              <el-input
                v-noSpace
                v-model="contractFormData.remark"
                type="textarea"
                :rows="3"
                class="flex-1"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <el-form-item
              v-if="contractDialog.type == 'look'"
              label="审核意见："
              prop="auditOpinion"
            >
              <el-input
                v-noSpace
                v-model="contractFormData.auditOpinion"
                type="textarea"
                :rows="3"
                class="flex-1"
              />
            </el-form-item>
            <el-form-item label="合同附件：" prop="attachment">
              <div class="w-100 align flex-1">
                <el-row
                  v-for="(item, index) in JSON.parse(
                    contractFormData.attachment ? contractFormData.attachment : '[]'
                  )"
                  :key="index"
                >
                  <el-col :span="12">
                    <el-text type="primary">{{ item.name }}</el-text>
                  </el-col>
                  <el-col :span="12">
                    <el-link type="primary" @click="downloadFile(item.name, item.url)">
                      下载
                    </el-link>
                    <el-link
                      v-if="contractDialog.type !== 'look'"
                      type="danger"
                      @click="handleDeleteFile(index)"
                      class="ml-4"
                    >
                      删除
                    </el-link>
                    <!-- <el-link type="primary" class="ml-4" @click="preViewFile(item.name, item.url)">
                      预览
                    </el-link> -->
                  </el-col>
                </el-row>
              </div>
              <div>
                <!-- <el-upload v-model:file-list="fileInfoJson" multiple :show-file-list="true" :auto-upload="false"
                    ref="uploadRef" v-if="contractDialog.type !== 'look'" class="  items-center w-50">

                    <el-button type="primary">点击上传</el-button>

                  </el-upload> -->
                <FileUpload
                  v-if="contractDialog.type !== 'look'"
                  v-model:model-value="fileInfoJson"
                  uploadBtnText="点击上传"
                  :showTip="true"
                  :showDelBtn="false"
                  :data="{ bizType: 'contract' }"
                  :maxSize="5 * 1024 * 1024"
                  :showFileList="false"
                  @update:modelValue="handleUpdateFileInfoJson"
                />
              </div>
            </el-form-item>

            <!-- 配送信息 -->
            <div class="grid grid-cols-2">
              <div class="flex items-center">
                <el-form-item label="每单默认份数：" prop="perOrderConfirmCount">
                  <el-input-number
                    v-model="contractFormData.perOrderConfirmCount"
                    :min="0"
                    class="flex-1"
                  />
                </el-form-item>
              </div>
              <div class="flex items-center">
                <el-form-item label="默认人数单价：" prop="perMealPrice">
                  <el-input-number
                    v-model="contractFormData.perMealPrice"
                    :min="0.01"
                    :precision="2"
                    :step="0.01"
                  />
                </el-form-item>
              </div>
              <div class="flex items-center">
                <el-form-item label="每单起订份数：" prop="perOrderDeliveryCount">
                  <el-input-number
                    v-model="contractFormData.perOrderDeliveryCount"
                    :min="0"
                    class="flex-1"
                  />
                </el-form-item>
              </div>
              <!-- <div class="flex items-center">
                <el-form-item label="最小起金额：" prop="minOrderAmount" label-width="130px">
                  <el-input-number
                    v-model="contractFormData.minOrderAmount"
                    :min="0"
                    class="flex-1"
                  />
                </el-form-item>
              </div> -->
            </div>

            <!-- 系统建议 -->
            <!-- <div class="w-full">
                <div class="flex items-center">
                  <el-form-item
                    label="是否系统生成建议订单："
                    prop="isSystemCreateDelivery"
                    label-width="180px"
                    class="w-full"
                  >
                    <el-radio-group v-model="contractFormData.isSystemCreateDelivery">
                      <el-radio :value="1">是</el-radio>
                      <el-radio :value="0">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </div> -->

            <!-- 配送规则 -->
            <!-- <div v-if="contractFormData.isSystemCreateDelivery === 1" class="mb-2">
                <div class="flex items-center gap-4 mb-2">
                  <el-form-item label="起送时间：" prop="deliveryStartDate" label-width="100px">
                    <el-date-picker
                      v-model="contractFormData.deliveryStartDate"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      type="date"
                      placeholder="选择日期"
                      :disabled-date="disabledDate"
                    />
                  </el-form-item>
                </div>
                <div class="flex">
                  <el-form-item label="配送规则：" prop="deliveryCron" label-width="100px">
                    <Vue3Cron
                      v-if="contractDialog.visible"
                      v-model:value="contractFormData.deliveryCron"
                    />
                  </el-form-item>
                </div>
              </div> -->
          </el-form>
          <!-- <div class="mb-2">
              <div class="flex justify-end mt-4">
                <el-button
                  v-if="contractDialog.type !== 'look'"
                  type="primary"
                  class="!rounded-button"
                  @click="handleOpenProductDialog"
                >
                  添加产品
                </el-button>
              </div>

              <el-table :data="tempProdData" border class-name="mt-4">
                <el-table-column prop="productCode" label="产品编号" width="120" />
                <el-table-column prop="productName" label="产品名称" width="120" />
                <el-table-column prop="quantity" label="每份数量(kg)" width="120" />
                <el-table-column prop="price" label="单价(元)" width="120" />
                <el-table-column prop="remark" label="备注" />

                <el-table-column v-if="contractDialog.type !== 'look'" label="操作">
                  <template #default="scope">
                    <el-button link type="danger" @click="handleDeleteProduct(scope.row)">
                      删除
                    </el-button>
                    <el-button link type="danger" @click="handleUpdateProduct(scope.row)">
                      修改
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-if="prodTotal > 0"
                v-model:total="prodTotal"
                v-model:page="prodQueryParams.pageNum"
                v-model:limit="prodQueryParams.pageSize"
                @pagination="handleQuery"
              />
            </div> -->

          <!-- 提交按钮 -->
          <div class="flex justify-center">
            <el-button
              v-if="contractDialog.type !== 'look'"
              v-debounce="handleSubmitContract"
              type="primary"
              class="!rounded-button"
              :disabled="loading"
            >
              提交
            </el-button>
          </div>
        </div>
      </div>
      <!-- </el-scrollbar> -->
    </el-dialog>

    <!-- 添加产品 -->
    <!-- <el-dialog
      v-model="prodDialog.visible"
      :title="prodDialog.title"
      width="500px"
      @close="handleCloseProdDialog"
    >
      <el-form
        ref="prodFormRef"
        :model="prodFormData"
        label-width="100px"
        class="dialog-form"
        :rules="prodRules"
      >
        <el-form-item label="产品类型" prop="productType">
          <el-select v-model="prodFormData.productType" placeholder="请选择产品类型" disabled>
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.categoryName"
              :value="item.categoryName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品编号" prop="productCode">
          <el-select v-model="prodFormData.productCode" placeholder="请选择产品编号" disabled>
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.code"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-select
            v-model="prodFormData.productName"
            placeholder="请输入产品名称"
            :disabled="prodDialog.type === 'update'"
            @visible-change="handleProductNameChange"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.productName"
              :value="item.productName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="每份数量" prop="quantity">
          <el-input-number v-model="prodFormData.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model="prodFormData.price" :min="0.01" :precision="2" :step="0.01" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-noSpace
            v-model="prodFormData.remark"
            type="textarea"
            placeholder="请输入备注"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button v-debounce="handleSaveProd" type="primary">保存</el-button>
          <el-button
            v-if="prodDialog.type === 'add'"
            type="primary"
            @click="handleSaveProd('again')"
          >
            保存并继续新增
          </el-button>
        </div>
      </template>
    </el-dialog> -->
    <!-- 审核 -->
    <el-dialog
      v-model="appDialog.visible"
      :title="appDialog.title"
      width="500px"
      @close="handleCloseApplyDialog"
    >
      <el-input
        v-noSpace
        v-model="approvedRemakeForm.approvedRemake"
        type="textarea"
        placeholder="请输入审核意见"
        maxlength="500"
        show-word-limit
      />

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button type="primary" @click="handleAppPass('pass')">通 过</el-button>
          <el-button type="primary" @click="handleAppPass('noPass')">拒绝</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog
      v-model="preViewVisible"
      :show-close="false"
      title="图片预览"
      width="500px"
      class="preview-dialog"
    >
      <div class="preview-content">
        <el-image :src="previewImageUrl" width="300" alt="图片预览" class="preview-image">
          <template #error>
            <div class="image-slot">
              <el-icon><icon-picture /></el-icon>
            </div>
          </template>
        </el-image>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { UploadInstance, UploadUserFile } from "element-plus";
import { Picture as IconPicture } from "@element-plus/icons-vue";
import { FormItemRule } from "element-plus/es";
import cusInfoApi, {
  salesContractQuery,
  salesContract,
  salesContractDetailQuery,
  salesContractDetail,
} from "@/api/cusManage/cusInfo";
import configApi, { ConfigType } from "@/api/config/config";
import FileAPI from "@/api/file";
// import productInfoAPI from "@/api/productInfo/productInfo";
import organizationalAPI, { Employee } from "@/api/basicData/organizational";
import UserAPI from "@/api/system/user";

const previewImageUrl = ref();
const preViewVisible = ref(false);
const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};
// //产品名称改变
// function handleProductNameChange() {
//   const product = productList.value.find((item) => item.productName === prodFormData.productName);
//   if (product) {
//     prodFormData.productCode = product.code;
//     prodFormData.productType = product.categoryName;
//   }
// }

//交易条款列表
const contractList = ref<any[]>([]);
function getContractList() {
  configApi.getConfigListByType(ConfigType.TRANSACTION_TERMS).then((res) => {
    console.log(res);
    contractList.value = res;
  });
}

//付款条款列表
const paymentTermsList = ref<any[]>([]);
function getPaymentTermsList() {
  configApi.getConfigListByType(ConfigType.PAYMENT_TERMS).then((res) => {
    console.log(res);
    paymentTermsList.value = res;
  });
}
const breachList = ref<any[]>([]);
function getBreachList() {
  configApi.getConfigListByType(ConfigType.BREACH_TERMS).then((res) => {
    console.log(res);
    breachList.value = res;
  });
}

//合同表单校验
const contractRules: Record<string, FormItemRule[]> = {
  companyCode: [{ required: true, message: "请选择客户编号", trigger: "blur" }],
  companyName: [{ required: true, message: "请输入客户名称", trigger: "blur" }],

  status: [{ required: true, message: "请选择合同状态", trigger: "change" }],
  signDate: [{ required: true, message: "请选择签订日期", trigger: "change" }],
  expireDate: [
    { required: true, message: "请选择到期日期", trigger: "change" },
    {
      validator: (rule, value, callback) => {
        const signDate = contractFormData.signDate;
        if (value && signDate && new Date(value) < new Date(signDate)) {
          callback(new Error("到期日期不得早于签订日期"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  paymentTerms: [{ required: true, message: "请选择付款条款", trigger: "change" }],
  transactionTerms: [{ required: true, message: "请选择交易条款", trigger: "change" }],
  breachType: [{ required: true, message: "请选择违约条款", trigger: "change" }],
  discountRate: [{ required: true, message: "请输入折扣率", trigger: "blur" }],

  contactPerson: [{ required: true, message: "请输入联系人", trigger: "blur" }],

  salesMan: [{ required: true, message: "请输入业务员", trigger: "blur" }],

  attachment: [{ message: "请上传合同附件", trigger: "change" }],
  perOrderConfirmCount: [{ required: true, message: "请输入每单默认份数", trigger: "change" }],
  perMealPrice: [{ required: true, message: "请输入默认人数单价", trigger: "change" }],
  perOrderDeliveryCount: [{ required: true, message: "请输入每单起订份数", trigger: "change" }],
  isSystemCreateDelivery: [
    { required: true, message: "请选择是否系统生成建议订单", trigger: "change" },
  ],
  deliveryStartDate: [{ required: true, message: "请选择起送时间", trigger: "change" }],
  deliveryCron: [{ required: true, message: "请选择配送规则", trigger: "blur" }],
  remark: [
    //最大500
    { min: 0, max: 500, message: "备注长度在 0 到 500 个字符", trigger: "blur" },
  ],
};

//联系人列表
const contactList = ref<any[]>([]);

//查询客户所有信息
function getCusInfo(code: string) {
  contractFormData.contactPerson = ""; // 清空联系人信息
  contractFormData.contactInfo = ""; // 清空联系人电话
  contractFormData.companyName = "";
  if (!code) return;

  cusInfoApi
    .getPage({ code, pageNum: 1, pageSize: 10 })
    .then((res) => {
      console.log(res, "res");
      contractFormData.companyName = res.records[0].companyName;
      getContactList(code);
    })
    .finally(() => {});
}
//根据客户查询联系人
function getContactList(code: string) {
  console.log(code, "code");

  if (!code) return;
  cusInfoApi.getContactPage({ pageNum: 1, pageSize: 99, parentCode: code }).then((res) => {
    console.log(res, "根据客户查询联系人");
    //将联系人列表赋值给contactList.value
    contactList.value = res.map((item: any) => {
      return {
        id: item.id,
        tel: item.tel,

        label: item.contactPerson,
        value: item.id.toString(),
      };
    });
  });
}

//根据联系人获取电话
function getContactInfo(val: number) {
  contractFormData.contactInfo = contactList.value.find((item) => item.value === val)?.tel;
  // if (val) {
  //   const contact = contactList.value.find((item) => item.id === val);
  //   if (contact) {
  //     contractFormData.contactInfo = contact.tel;
  //   }
  // }
}

//配送规则
const baseCron = reactive<{ deliveryDays?: number; deliveryWeeks?: []; deliveryType?: number }>({
  deliveryDays: undefined,
  deliveryWeeks: undefined, // 选中周几的数组，例如 [1, 3] 表示周一和周三
  deliveryType: undefined, // 单选框的值
});

//产品弹窗
const prodDialog = reactive({
  visible: false,
  title: "添加产品",
  type: "add", // add or update
});

//产品表单校验
const prodRules: Record<string, FormItemRule[]> = {
  productCode: [{ required: true, message: "请输入产品编号", trigger: "blur" }],
  productName: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
  productType: [{ required: true, message: "请输入产品类型", trigger: "blur" }],

  quantity: [{ required: true, message: "请输入每份数量", trigger: "blur" }],
  price: [{ required: true, message: "请输入单价", trigger: "blur" }],
  remark: [
    //最大500
    { min: 0, max: 500, message: "备注长度在 0 到 500 个字符", trigger: "blur" },
  ],
};

const prodFormRef = ref();

//合同数据
let prodFormData = reactive<salesContractDetail>({});

//暂存产品信息
// const tempProdData = ref<salesContractDetail[]>([]);

function handleOpenProductDialog() {
  prodDialog.visible = true;
  prodDialog.title = "添加产品";
  prodDialog.type = "add";
}

// //临时删除产品
// const handleDeleteProduct = (row: any) => {
//   tempProdData.value = tempProdData.value.filter(
//     (item: any) => item.productCode !== row.productCode
//   );
// };
// //修改产品
// const handleUpdateProduct = (row: any) => {
//   //打开弹窗
//   prodDialog.visible = true;
//   prodDialog.title = "修改产品";
//   prodDialog.type = "update";
//   Object.assign(prodFormData, row);
// };
//保存产品信息

// function handleSaveProd(type?: string) {
//   // 校验表单
//   prodFormRef.value.validate((valid: boolean) => {
//     if (!valid) return;

//     const existingProd = tempProdData.value.find(
//       (item) => item.productCode === prodFormData.productCode
//     );
//     if (existingProd) {
//       // 产品已存在，直接修改产品信息

//       if (prodDialog.type === "add") {
//         ElMessageBox.confirm("产品已存在，将会修改该产品信息", "提示", {
//           confirmButtonText: "确定",
//           cancelButtonText: "取消",
//           type: "warning",
//         }).then(() => {
//           Object.assign(existingProd, prodFormData);
//           if (type !== "again") {
//             handleCloseProdDialog();
//           } else {
//             handleClearForm();
//           }
//         });
//       } else {
//         Object.assign(existingProd, prodFormData);
//         handleCloseProdDialog();
//       }
//     } else {
//       // 产品不存在，添加到产品列表
//       tempProdData.value.push({ ...prodFormData });
//       if (type !== "again") {
//         handleCloseProdDialog();
//       } else {
//         handleClearForm();
//       }
//     }
//   });
// }

// //关闭handleProdDialog
// function handleCloseProdDialog() {
//   handleClearForm();
//   prodDialog.visible = false;
// }

//清空表单
function handleClearForm() {
  prodFormRef.value.resetFields();
  prodFormData.productCode = "";
  prodFormData.productName = "";
  prodFormData.productType = "";
  prodFormData.quantity = undefined;
  prodFormData.price = undefined;
  prodFormData.remark = "";
  prodFormData.id = undefined;
  prodFormRef.value.clearValidate();
}

//审核弹窗
const appDialog = reactive({
  visible: false,
  title: "审核",
});
//审核意见
const approvedRemakeForm = ref();

//打开审核弹窗
function handleOpenApplyDialog(row: any) {
  appDialog.visible = true;
  appDialog.title = "审核";
  approvedRemakeForm.value = row;
}

//关闭审核弹窗
function handleCloseApplyDialog() {
  appDialog.visible = false;
  approvedRemakeForm.value.approvedRemake = "";
}

//审核通过或拒绝
function handleAppPass(type: string) {
  if (type === "pass") {
    cusInfoApi
      .auditContract({
        id: approvedRemakeForm.value.id,
        auditOpinion: approvedRemakeForm.value.approvedRemake,
        status: "1",
      })
      .then(() => {
        appDialog.visible = false;
      })
      .finally(() => {
        handleQuery();
      });
  } else if (type === "noPass") {
    cusInfoApi
      .auditContract({
        id: approvedRemakeForm.value.id,
        auditOpinion: approvedRemakeForm.value.approvedRemake,
        status: "2",
      })
      .then(() => {
        appDialog.visible = false;
      })
      .finally(() => {
        handleQuery();
      });
  }
}

//所有客户编号-下拉框
// const codeProps = {
//   // label: "code-companyName",
//   label: "companyName",
//   value: "code",
// };
const allCompanyCode = ref<{ companyName: string; code: string }[]>([]);

const salesPersonList = ref<any[]>([]);
const salesProps = {
  label: "name",
  value: "id",
};
const queryFormRef = ref(ElForm);
const queryParams = reactive<salesContractQuery>({
  pageNum: 1,
  pageSize: 10,
});

const prodQueryParams = reactive<salesContractQuery>({
  pageNum: 1,
  pageSize: 20,
});

//录入日期日期框可选日期
const shortcuts = [
  {
    text: "过去三天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "过去一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "过去三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

const pageData = ref<salesContract[]>();

const total = ref(0);

const prodTotal = ref(0);

//弹窗配置
//新增弹窗
const contractDialog = reactive({
  title: "",
  visible: false,
  type: "",
});

//基础信息提交表单
const contractFormRef = ref(ElForm);

const loading = ref(false);

const contractFormData = reactive<salesContract>({
  deliveryCron: "0 0 0 1/1 * ?",
  isSystemCreateDelivery: 1,
  discountRate: 0,
  // minOrderAmount: 0,
});

const fileInfoJson = ref<UploadUserFile[]>([]);

// 查询
function handleQuery() {
  loading.value = true;

  const query = { ...queryParams };
  if (queryParams.signDate && queryParams.signDate.length === 2) {
    query.signDateStart = queryParams.signDate[0];
    query.signDateEnd = queryParams.signDate[1];
    delete query.signDate;
  } else {
    query.signDateStart = undefined;
    query.signDateEnd = undefined;
    delete query.signDate;
  }
  if (queryParams.expireDate && queryParams.expireDate.length === 2) {
    query.expireDateStart = queryParams.expireDate[0];
    query.expireDateEnd = queryParams.expireDate[1];
    delete query.expireDate;
  } else {
    query.expireDateEnd = undefined;
    query.expireDateStart = undefined;
    delete query.expireDate;
  }
  cusInfoApi
    .getContractList(query)
    .then((data: any) => {
      pageData.value = data.list;

      total.value = data.total;
      // allContractCode.value = data.list.map((item: any) => {
      //   return {
      //     value: item.code,
      //     label: item.code,
      //   };
      // });
    })
    .catch((err) => {
      // ElMessage.error(`${err}`);
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.companyCode = undefined;
  queryParams.salesMan = undefined;

  handleQuery();
}

// 新增/修改/查看
function handleOpenDialog(row?: any, type?: string) {
  console.log(row);

  contractDialog.type = type || "";
  contractDialog.visible = true;
  if (type === "look") {
    //查看,不可编辑
    getContactList(row.companyCode);
    contractDialog.title = "查看客户合同";
    // cusInfoApi
    //   .getContractDetail({ ...prodQueryParams, contractCode: row.code })
    //   .then((res) => {
    //     // tempProdData.value = res.list;
    //     // prodTotal.value = res.total;
    //   })
    //   .catch((err) => {
    //     // ElMessage.error(`${err}`);
    //   });
    Object.assign(contractFormData, row);
    contractFormData.paymentTerms = row.paymentTerms.split(",");
    contractFormData.transactionTerms = row.transactionTerms.split(",");
    contractFormData.breachType = row.breachType.split(",");
  } else if (type == "update") {
    //修改
    contractDialog.title = "修改客户合同";
    console.log(row.parentCode);
    getContactList(row.companyCode);
    // cusInfoApi
    //   .getContractDetail({ ...prodQueryParams, contractCode: row.code })
    //   .then((res) => {
    //     // tempProdData.value = res.list;
    //     // prodTotal.value = res.total;
    //   })
    //   .catch((err) => {
    //     // ElMessage.error(`${err}`);
    //   })
    //   .finally(() => {
    //     loading.value = false;
    //   });
    //回显
    Object.assign(contractFormData, row);
    contractFormData.paymentTerms = row.paymentTerms.split(",");
    contractFormData.transactionTerms = row.transactionTerms.split(",");
    contractFormData.breachType = row.breachType.split(",");
  } else {
    contractDialog.title = "新增客户合同";
  }
}

function handleUpdateFileInfoJson(fileInfoJson: any) {
  //将fileInfoJson的name改为file_name,url改为file_url，并与infoFormData.fileInfoJson合并

  // fileInfoJson.map((item: any) => {
  //   item.file_name = item.name;
  //   item.file_url = item.url;
  // });

  let submitFileInfo = JSON.parse(contractFormData.attachment || "[]");
  submitFileInfo = [fileInfoJson[fileInfoJson.length - 1], ...submitFileInfo];

  console.log(fileInfoJson, contractFormData.attachment, "fileInfoJson");

  contractFormData.attachment = JSON.stringify(submitFileInfo);
}

//提交成功
function handleSubmitContract() {
  // console.log("合同提交参数：params", contractFormData);

  // 校验表单数据是否合法
  contractFormRef.value?.validate((valid: any) => {
    if (!valid) return;
    // if (tempProdData.value.length === 0) {
    //   ElMessage.error("请选择产品信息");
    //   return;
    // }
    if (JSON.parse(contractFormData.attachment || "[]").length === 0) {
      ElMessage.error("请上传附件");
      return;
    }
    loading.value = true;

    // const params: any = { contract: contractFormData, productList: tempProdData.value };
    const params: any = { contract: contractFormData };
    // params.contract.deliveryCron = '0/5 * * * * ?'
    params.contract.isVendor = 0;
    console.log("合同提交参数：params", params);
    params.contract.paymentTerms = contractFormData.paymentTerms?.join(",");
    params.contract.transactionTerms = contractFormData.transactionTerms?.join(",");
    params.contract.breachType = contractFormData.breachType?.join(",");
    cusInfoApi
      .updateContract(params)
      .then(() => {
        handleCloseDialog();
        ElMessage.success("操作成功");
        handleQuery();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

// 清空客户表单数据
function clearFormData() {
  let data: salesContract = {
    id: undefined,
    companyCode: undefined,
    companyName: undefined,
    status: undefined,
    signDate: undefined,
    expireDate: undefined,
    paymentTerms: undefined,
    transactionTerms: undefined,
    contactPerson: undefined,
    contactInfo: undefined,
    salesMan: undefined,
    remark: undefined,
    auditOpinion: undefined,
    perOrderConfirmCount: undefined,
    perMealPrice: undefined,
    perOrderDeliveryCount: undefined,
    isSystemCreateDelivery: 1,
    deliveryStartDate: undefined,
    attachment: undefined,
    deliveryCron: "0 0 0 1/1 * ?",
    discountRate: 0,
    breachType: undefined,
  };
  //清空联系人
  contactList.value = [];
  //清空产品信息列表
  // tempProdData.value = [];
  prodTotal.value = 0;
  fileInfoJson.value = [];

  Object.assign(contractFormData, data);
}

// 关闭弹窗
function handleCloseDialog() {
  contractDialog.visible = false;
  contractFormRef.value?.resetFields();
  clearFormData();
}

/**
 * 删除合同信息
 * @param  id? number 客户合同id
 * @returns
 */

function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除合同信息?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      cusInfoApi
        .deleteContract(id)
        .then((data) => {
          ElMessage.success("删除成功");

          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
          handleQuery();
        })
        .finally(() => {
          handleQuery();
          loading.value = false;
        });
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

//下载附件
function downloadFile(name: string, filePath: string) {
  if (filePath) {
    FileAPI.downloadFile(filePath, name)
      .then((res) => {
        ElMessage.success("下载成功");
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      });
  }
}
const handleDeleteFile = (index: number) => {
  let submitFileInfo = JSON.parse(contractFormData.attachment || "[]");
  submitFileInfo.splice(index, 1);
  fileInfoJson.value.splice(index, 1);
  console.log(submitFileInfo, "submitFileInfo");
  contractFormData.attachment = JSON.stringify(submitFileInfo);
};

const preViewFile = (name: string, filePath: string) => {
  FileAPI.previewFile(filePath).then((res) => {
    console.log(res, "res");
    //将流放到页面上预览
    let blob = new Blob([res.data]);
    let reader = new FileReader();

    reader.readAsDataURL(blob); // 转换为base64
    reader.onload = function () {
      console.log(reader.result, "reader.result");
      previewImageUrl.value = reader.result;
      preViewVisible.value = true;
    };
  });
};

//查询所有客户和业务员信息
function handleAllCompanyQuery() {
  cusInfoApi.getPage({ pageNum: 1, pageSize: 999 }).then((data: any) => {
    allCompanyCode.value = data.records.map((item: any, idx: number) => ({
      value: item.code,
      label: `${item.code} - ${item.companyName}`,
    }));
  });

  UserAPI.getPage({ pageNum: 1, pageSize: 999, roleName: "salesMan" }).then((data) => {
    salesPersonList.value = data.list.map((item: any) => ({
      value: item.id,
      label: item.name,
    }));
    console.log(data, "data");
  });
}

onMounted(() => {
  handleQuery();
  // getProductName();
  getContractList();
  getPaymentTermsList();
  getBreachList();
  handleAllCompanyQuery();
});
</script>

<style lang="scss" scoped></style>
